import { AdminService } from '@/api/AdminService'
import { setUser, removeUser, setToken, removeToken } from '@/utils/auth'
import router from '@/router'

const user = {
  actions: {
    // 用户名登录
    login({ commit }, loginForm) {
      return new Promise((resolve, reject) => {
        AdminService.login(loginForm).then(result => {
          setUser(result)
          setToken(result.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        AdminService.logout(state.token).then(() => {
          removeUser()
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    WebLogOut({ commit }) {
      return new Promise(resolve => {
        removeUser()
        removeToken()
        router.push({ path: '/login' })
        resolve()
      })
    },

    // 没有权限
    NoPermission({ commit }) {
      return new Promise(resolve => {
        router.push({ path: '/401' })
        resolve()
      })
    }
  }
}

export default user
